package com.lx.composetest

import android.content.Context
import android.net.wifi.WifiManager
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress


class MainActivity : ComponentActivity() {

    private val multicastAddress = "224.123.1.1" // Replace with your multicast address
    private val port = 44444 // Replace with your port

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // Enable WiFi multicast reception
//        val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
//        val multicastLock = wifiManager.createMulticastLock("multicastLock")
//        multicastLock.setReferenceCounted(true)
//        multicastLock.acquire()
//        send()
//        CoroutineScope(Dispatchers.Main).launch {
//            while (true) {
//                multicastLock.acquire()
//                delay(10000)
//            }
//        }

        setContent {
            var message by remember {
                mutableStateOf("Waiting for UDP multicast...")
            }

            LaunchedEffect(Unit) {
                startUdpReceiver { receivedMessage ->
                      message = receivedMessage
                }
            }

            UdpMulticastReceiverScreen(message)
        }
    }

    private fun startUdpReceiver(onMessageReceived: (String) -> Unit) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                Log.d("UDPReceiver", "start listen")
                val buffer = ByteArray(1024)
                val socket = DatagramSocket(port)
                socket.broadcast = true

                while (true) {
                    val packet = DatagramPacket(buffer, buffer.size)
                    socket.receive(packet)
                    val message = String(packet.data, 0, packet.length)
                    Log.d("UDPReceiver", "Received message: $message")
                    onMessageReceived(message)
                }
            } catch (e: Exception) {
                e.printStackTrace()
                Log.e("UDPReceiver", "Error receiving UDP broadcast", e)
            }
        }
    }


}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun UdpMulticastReceiverScreen(message: String) {
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("UDP Multicast Receiver") }
            )
        }
    ) { p ->
        p.calculateTopPadding()
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            if (message.isNotEmpty()) {
                Text(text = "收到的数据：")
            }
            Box(modifier = Modifier.fillMaxSize()
                .background(color = Color.Red, shape = RoundedCornerShape(8.dp))) {
                Text(text = message, modifier = Modifier.padding(top = 30.dp))
            }
        }
    }
}